/**
 * Meituan.com Inc.
 * Copyright (c) 2010-2018 All Rights Reserved.
 */
package concurrent.blockingQueue;

import org.junit.Test;

import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.locks.LockSupport;

/**
 * 里面只能保存一个元素
 * 调用put会阻塞，直到元素被取走才返回
 * 没有元素时take会阻塞
 *
 * @author tuyou@meituan.com
 * @version v0.1 2018-11-13 10:28 AM tuyou Exp $$
 */
public class SynchronousQueueTest {

    @Test
    public void put() throws InterruptedException {

        SynchronousQueue<String> queue = new SynchronousQueue<>();
        queue.put("1"); //阻塞
        System.out.println("1");
        queue.put("2");
        System.out.println("2");
    }

    @Test
    public void take() throws InterruptedException {
        SynchronousQueue queue = new SynchronousQueue();

        new Thread() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                    System.out.println("准备第一次take");
                    System.out.println("take元素：" + queue.take());
                    System.out.println("第一次take完成，准备第二次take");
                    System.out.println("take元素：" + queue.take());
                    System.out.println("第二次take完成");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        System.out.println("put元素");
        queue.put(1);
        System.out.println("put完成");

        LockSupport.park(this);
    }
}